use bitflags::bitflags as inner_bitflags;

macro_rules! bitflags {
    (
        $(#[$outer:meta])*
        pub struct $BitFlags:ident: $T:ty {
            $(
                $(#[$inner:ident $($args:tt)*])*
                const $Flag:ident = $value:expr;
            )+
        }
    ) => {
        // First, use the inner bitflags
        inner_bitflags! {
            #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy, Default)]
            $(#[$outer])*
            pub struct $BitFlags: $T {
                $(
                    $(#[$inner $($args)*])*
                    const $Flag = $value;
                )+
            }
        }

        impl $BitFlags {
            #[deprecated = "use the safe `from_bits_retain` method instead"]
            pub unsafe fn from_bits_unchecked(bits: $T) -> Self {
                Self::from_bits_retain(bits)
            }
        }

        // Secondly, re-export all inner constants
        // (`pub use self::Struct::*` doesn't work)
        $(
            $(#[$inner $($args)*])*
            pub const $Flag: $BitFlags = $BitFlags::$Flag;
        )+
    }
}

pub const CLOCK_REALTIME: usize = 1;
pub const CLOCK_MONOTONIC: usize = 4;

bitflags! {
    pub struct EventFlags: usize {
        const EVENT_NONE = 0;
        const EVENT_READ = 1;
        const EVENT_WRITE = 2;
    }
}

bitflags! {
    pub struct MapFlags: usize {
        // TODO: Downgrade PROT_NONE to global constant? (bitflags specifically states zero flags
        // can cause buggy behavior).
        const PROT_NONE = 0x0000_0000;

        const PROT_EXEC = 0x0001_0000;
        const PROT_WRITE = 0x0002_0000;
        const PROT_READ = 0x0004_0000;

        const MAP_SHARED = 0x0001;
        const MAP_PRIVATE = 0x0002;

        const MAP_FIXED = 0x0004;
        const MAP_FIXED_NOREPLACE = 0x000C;

        /// For *userspace-backed mmaps*, return from the mmap call before all pages have been
        /// provided by the scheme. This requires the scheme to be trusted, as the current context
        /// can block indefinitely, if the scheme does not respond to the page fault handler's
        /// request, as it tries to map the page by requesting it from the scheme.
        ///
        /// In some cases however, such as the program loader, the data needs to be trusted as much
        /// with or without MAP_LAZY, and if so, mapping lazily will not cause insecureness by
        /// itself.
        ///
        /// For kernel-backed mmaps, this flag has no effect at all. It is unspecified whether
        /// kernel mmaps are lazy or not.
        const MAP_LAZY = 0x0010;
    }
}
bitflags! {
    pub struct MunmapFlags: usize {
        /// Indicates whether the funmap call must implicitly do an msync, for the changes to
        /// become visible later.
        ///
        /// This flag will currently be set if and only if MAP_SHARED | PROT_WRITE are set.
        const NEEDS_SYNC = 1;
    }
}
